import { useState, useEffect, useMemo } from 'react';
import { Input } from 'antd';
import AreaCheckboxModal from './AreaCheckboxModal';
import { getAllArea } from "@/services/common";

export default ({ page = 'common-address-search', initSelectData = [], handleChange, onChange }) => {

  const [visible, setVisible] = useState(false);
    //省市区信息
	const [data, setData] = useState([]);
  const [selectData, setSelectData] = useState(initSelectData);

  const showValue = useMemo(()=>{
    if(selectData?.length){
      let str = '已选择';
      selectData.map((item, index)=>{
        str += `${index ? '、' : ''}${item.name}(${item.childs?.length})`
      })
     return str;
    }
  }, [selectData])

  useEffect(()=>{
   getAreaData();
  }, [])

    //获取省市区地址信息
	const getAreaData = async () => {
		const { data, success } = await getAllArea();
		if (success) {
			setData(data);
		}
	};

  const areaCheckboxModalProps = {
    page,
    allData: data, 
    selectedList: selectData,
    handleOk(areaIds, treeData){
      setSelectData(treeData);
      handleChange?.(areaIds, treeData);
    },
    handleCancel(){
      setVisible(false);
    }
  }

  return <>
    <Input 
      placeholder='请选择地址' 
      value={showValue} 
      allowClear
      onClick={()=>setVisible(true)} 
      onChange={() => {
        if(onChange){
          onChange();
          setSelectData([]);
        }
      }} 
    />
    { visible && <AreaCheckboxModal {...areaCheckboxModalProps} />}
  </>
}